package com.finace.money.net.socket;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.finace.money.common.Constant;
import com.finace.money.common.util.LogUtil;
import com.finace.money.common.util.MessageParseUtil;
import com.finace.money.common.util.MessageSendUtil;
import com.finace.money.common.util.UIUtil;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhangpeng on 2017/12/8.
 */

public class ConnManager {

    private static WebSocketClient socket;
    //队列，封装发送的信息
    private static ConnManager instance;
    private Timer timer;

    private ConnManager() {
    }

    public static ConnManager getInstance() {
        if (instance == null) {
            synchronized (ConnManager.class) {
                if (instance == null) {
                    instance = new ConnManager();
                }
            }
        }
        return instance;
    }

    /**
     * 连接
     *
     * @return
     */
    public void connect() {

        String suri = String.format(Locale.getDefault(), Constant.BASE_SOCKET_URL);
        if (socket == null || socket.isClosed()) {

            URI uri = URI.create(suri);

            socket = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.d("connect", "连接成功");
                    if (null != timer) {
                        timer.cancel();
                    }
                    mListener.pushData(PushReceiver.CONN_SUCCESS);
                    //查询合约列表
                    MessageSendUtil.QueryProduct();
                    //心跳
                    MessageSendUtil.HEARTBEAT();
                }

                @Override
                public void onMessage(String message) {

                    MessageParseUtil.parseData(message, mListener);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
//                    reConnect();
                    LogUtil.d("connect", "closed:" + reason);
                }

                @Override
                public void onError(Exception ex) {

                    reConnect();
                    Log.d("connect", "onError: " + ex.toString());
                }


            };
            socket.connect();
        }
    }

    public WebSocketClient getSocket() {
        return socket;
    }


    public void sendMessage(String msg) {
        try {
            if (null != socket) {
                socket.send(msg);
            }
        } catch (WebsocketNotConnectedException e) {
            reConnect();
        }

    }

    public void reConnect() {
        if (!isNetConnect()) {
            return;
        }
        if (socket != null) {
            socket.close();
            socket = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.d("connect", "10S后断线重连");
                connect();
            }
        }, 10000, 10000);


    }


    public boolean getStatus() {
        return socket == null || socket.isClosed();
    }


    /**
     * 关闭连接
     */
    public void disConnect() {
        if (socket != null && !socket.isClosed()) {
            socket.close();
            socket = null;
        }
        MessageSendUtil.killTime();

    }


    public interface ConnectionListener {
        void pushData(String str);
    }

    private ConnectionListener mListener;

    public void setConnectionListener(ConnectionListener listener) {
        this.mListener = listener;
    }


    private boolean isNetConnect() {
        ConnectivityManager connectivity = (ConnectivityManager) UIUtil.getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

}
